package com.admin.service.impl;

import com.admin.entity.*;
import com.admin.mapper.AdminMapper;
import com.admin.mapper.GroupMapper;
import com.admin.mapper.StationMapper;
import com.admin.mapper.ThemeMapper;
import com.admin.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.token.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@SuppressWarnings("ALL")
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {

    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private IAdminService iAdminService;
    @Autowired
    private IRegionService iRegionService;
    @Autowired
    private IProvinceService iProvinceService;
    @Autowired
    private IAddressService iAddressService;
    @Autowired
    private IWelcomePageService iWelcomePageService;
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private ThemeMapper themeMapper;


    /**
     * 根据酒店名称查找酒店对象
     * @param pms
     * @return
     */
    public Station findByPms(String pms)
    {
        QueryWrapper q = new QueryWrapper();
        q.eq("pms_hotel_name",pms);
        return stationMapper.selectOne(q);
    }




    //判断站点Id存在
    @Override
    public boolean findById(Integer id) {
        Station station = stationMapper.selectById(id);
        if (station == null) {
            return false;
        }
        return true;
    }

    //根据站点Id查询站点详表
    @Override
    public Map findByIdStation(Map m) {
        return stationMapper.findByIdStation(m);
    }

    //根据 id 查询 站点信息
    @Override
    public Station queryByIdStationId(int id) {

        return stationMapper.selectById(id);
    }

    /**
     * 计费管理火币充值_搜索框,模糊查询,分页
     *
     * @param page  layui分页参数
     * @param limit 分页参数
     * @param map   查询数据
     * @return
     */
    @Override
    public IPage querywocoinfenye(int page, int limit, Map map) {
        Page page1 = new Page(page, limit);
        IPage querywocoin = stationMapper.querywocoin(page1, map);
        return querywocoin;
    }

    /**
     * 可以根据编号/名称/日期/查询所有的站点
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @Override
    public IPage selectAllStation(int page, int limit, Map map) {
        if (map.get("token") != null) {
            //int id = Integer.parseInt(JwtUtil.getUsername((String) map.get("token")));
            String token = (String) map.get("token");
            String username = JwtUtil.getUsername(token);

            Admin admin = iAdminService.getAdminByUserName(username);
            Integer id = admin.getAdminId();


            String adminids=adminMapper.getAllChildUser(id);
            List adminidlist= Arrays.asList(adminids.split(","));
            map.put("token",adminidlist);
        }
        Page p = new Page(page, limit);
        return stationMapper.selectAllStation(p, map);
    }

    /**
     * 修改站点表的最大终端
     *
     * @param sr
     * @return
     */
    @Override
    public int editterminals(StationRecharge sr) {
        Station s = stationMapper.selectById(sr.getStationRechargeStationId());
        if (s.getStationMaximumNumberOfTerminals() == null) {
            s.setStationMaximumNumberOfTerminals(0);
        }
        s.setStationMaximumNumberOfTerminals(s.getStationMaximumNumberOfTerminals() + sr.getStationRechargeSum());
        return stationMapper.updateById(s);
    }

    /**
     * 站点密钥分页
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @Override
    public IPage selectPasswodFenye(int page, int limit, Map map) {
        Page page1 = new Page(page, limit);
        return stationMapper.selectPasswodFenye(page1, map);
    }

    /**
     * 站点密钥余额增加
     *
     * @param skr
     * @return
     */
    @Override
    public int updateStationYue(StationKeyRecharge skr) {
        //根据站点id查站点
        Station station = stationMapper.selectById(skr.getStationKeyRechargeStation());
        if (station.getStationKeyYue() == null) {
            station.setStationKeyYue(0);
        }
        station.setStationKeyYue(station.getStationKeyYue() + skr.getStationKeyRechargeSum());
        return stationMapper.updateById(station);
    }


    /**
     * 删除站点并且修改上级用户的火币数
     *
     * @param station
     * @return
     */
    @Override
    public int deleteStation(Station station) {
        int n = stationMapper.deleteById(station.getStationId());//删除站点
        int n2 = iAdminService.updateAdminCoin(station);//修改上级用户的火币数
        return n;
    }

    /*
    添加站点
     */
    @Override
    public int addstastion(Station station, String address) {
        //得到当前时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.now();
        String localTime = df.format(time);
        LocalDateTime l = LocalDateTime.parse(localTime, df);
        station.setStationCreateTime(l);
       /* int woshu = iAdminService.updataAdminmoney(station);//修改火币数
        if (woshu == -1) {
            return -1;
        }*/
        //得到区域id并将名称放入pojo
        int regionid = station.getStationArea();
        Region x = iRegionService.selregionByid(regionid);
        station.setStationQuyu(x.getRegionName());
        //得到省id并将名称放入pojo
        int provincecode = station.getStationProvince();
        Province p = iProvinceService.selectProvince(provincecode);
        station.setStationShen(p.getProvinceName());
        //将详细地址插入address表并且得到addressid
        int adds = iAddressService.add(address);
        station.setAddressId(adds);
        //创建站点编号
        //QueryWrapper o = new QueryWrapper();
        //o.eq("station_province", station.getStationProvince());
        //int m = stationMapper.selectCount(o) + 1;
        //station.setStationBh("" + station.getStationProvince() + m);
        station.setStationBh(maxStationID(station.getStationProvince()));
        int n = stationMapper.insert(station);
        //得到站点id
        int id = station.getStationId();
        iWelcomePageService.insertstationid(id);//将站点id添加到欢迎桌面

        //创建默认分组
       /* TGroup tGroup =  new TGroup();
        tGroup.setGroupStatus("启用");
        tGroup.setGroupStationId(id);
        tGroup.setGroupName("默认组");
        groupMapper.insert(tGroup);*/

        return n;
    }

    /**
     * 获取最大编号
     * @param pre
     * @return
     */
    private synchronized  String maxStationID(int pre){
        //System.out.println("pre="+pre);
        Long id = stationMapper.getMaxStation(pre/10000);
        if (id==null){
            return pre+"1";  //4300009
        }
        return id+1+"";

    }

    /**
     * 查找站点是否同名
     *
     * @return
     */
    @Override
    public Station findStationName(Station station) {
        QueryWrapper q = new QueryWrapper();
        q.ne("station_id", station.getStationId());
        q.eq("station_name", station.getStationName());
        Station s = stationMapper.selectOne(q);
        return s;
    }

    /**
     * 修改站点信息
     *
     * @return
     */
    @Override
    public int editStationMes(Station station, String address) {
        //得到区域id的名字并将名称放入pojo
        int regionid = station.getStationArea();
        Region x = iRegionService.selregionByid(regionid);
        station.setStationQuyu(x.getRegionName());
        //得到省id的名字并将名称放入pojo
        Integer provincecode = station.getStationProvince();
        if (provincecode!=null)
        {
            Province p = iProvinceService.selectProvince(provincecode);
            station.setStationShen(p.getProvinceName());
        }

        //修改站点的详细地址信息
        int updateAdddress = iAddressService.updateAddress(address, station.getAddressId());
        station.setAddressId(updateAdddress);
        int n = stationMapper.updateById(station);
        return n;
    }

    /**
     * 新增的时候判断站点名称是否重复
     */
    @Override
    public Station selstationName(Station station) {
        QueryWrapper p = new QueryWrapper();
        p.eq("station_name", station.getStationName());
        return stationMapper.selectOne(p);
    }

    /**
     * 分页查询可以删除的站点
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @Override
    public IPage selectAllDelStation(int page, int limit, Map map) {
        if (map.get("token") != null) {
            String token = (String) map.get("token");
            String username = JwtUtil.getUsername(token);
            Admin admin = iAdminService.getAdminByUserName(username);
            int id = admin.getAdminId();

            String adminids=adminMapper.getAllChildUser(id);
            List adminidlist= Arrays.asList(adminids.split(","));
            map.put("token",adminidlist);
        }
        Page p = new Page(page, limit);
        return stationMapper.selectAllDelStation(p, map);
    }


    /**
     * 判断用户名和旧密码是否一致
     *
     * @param station
     * @return
     */
    @Override
    public boolean selectUserPwd(Map<String, String> map) {
        String stationPhone = map.get("stationPhone");
        String jiupwd = map.get("jiupwd");
        if (stationPhone != null && jiupwd != null) {
            QueryWrapper q = new QueryWrapper();

            q.eq("station_phone", stationPhone);
            Station station = stationMapper.selectOne(q);
            if (station.getStationPassword().equals(jiupwd)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 修改站点用户密码
     *
     * @param station
     * @return
     */
    @Override
    public boolean updateUserPwd(Map<String, String> map) {
        Station station = new Station();
        station.setStationPhone(map.get("stationPhone"));
        station.setStationPassword(map.get("stationPassword"));
        UpdateWrapper w = new UpdateWrapper();
        if (station.getStationPhone() != null && station.getStationPassword() != null) {
            w.eq("station_phone", station.getStationPhone());
            int update = stationMapper.update(station, w);
            if (update != 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Map queryThemeAdmin(Integer station_id) {

        Map list = stationMapper.queryThemeAdmin(station_id);

        return list;
    }

    @Override
    public Station queryStationLogin(String username, String password) {
        Station station = stationMapper.queryStationLoginMapper(username, password);
        return station;
    }

    /**
     * 查所有版权授权
     */
    @Override
    public IPage selcopyrightstation(int page, int limit, String search, int copyrightid,String token ) {
       List adminidlist=new ArrayList();
        if(token!=null){
            String username = JwtUtil.getUsername(token);
            Admin admin =iAdminService.getAdminByUserName(username);
            int id = admin.getAdminId();
           // int id = Integer.parseInt(JwtUtil.getUsername(token));
           String adminids=adminMapper.getAllChildUser(id);
            adminidlist= Arrays.asList(adminids.split(","));
       }
        Page p = new Page(page, limit);
        IPage q = stationMapper.selCopyRightStation(p, search,copyrightid,adminidlist);
        return q;
    }

    /**
     * 获取站点编号，如果为null,则没有登录
     * @param stationId
     * @param token
     * @return
     */
    @Override
    public int queryStationLoginUser(Integer stationId,String token) {

        String id=JwtUtil.getStationId(token);

        if(id!=null){
            String newstation=stationId+"";
            if(newstation.equals(id)){
                return stationId;
            }
        }

        Integer adminId = iAdminService.selectAdminId(stationId);

        int i = iAdminService.selectQuanxian(adminId, token);

        return i;
    }

    @Override
    public int selectIdByStationBh(String stationBh) {
        return stationMapper.selectIdByStationBh(stationBh);
    }

    @Override
    public Station selectStationByStationBH(String bh) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("station_bh",bh);
        Station station = stationMapper.selectOne(queryWrapper);
        return station;
    }

    /**
     * 根据站点编号查找所有主题
     * @param station
     * @return
     */
    @Override
    public List getThemeByStation(Station station) {
        QueryWrapper queryWrapper  = new QueryWrapper();
        queryWrapper.select("group_desktop_configuration");
        queryWrapper.eq("group_station_id",station.getStationId());
        List<Integer> groupsList =  groupMapper.selectObjs(queryWrapper);
        if (groupsList!=null && groupsList.size()>0) {
            List list = themeMapper.selectBatchIds(groupsList);
            return list;
        }
        return null;
    }

    //普通用户获取所有站点
    @Override
    public IPage selectAllStation(int page, int limit, Map map, Admin admin) {
        String adminids=adminMapper.getAllChildUser(admin.getAdminId());
        List adminidlist= Arrays.asList(adminids.split(","));
        Page p = new Page(page,limit);
        map.put("token",adminidlist);
        return stationMapper.selectAllStation(p, map);
    }
}
